package com.maxmlr.framework.aop;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

/**
 * @ClassName AopProxyUtils
 * @Description TODO
 * @Author maxiao
 * @Date 2020/3/17 上午10:58
 * @Version V1.0
 */
public class AopProxyUtils {

    public static Object getTargetObject(Object proxy) throws Exception {
        if (Proxy.isProxyClass(proxy.getClass())) {
            return getProxyTargetObject(proxy);
        } else {
            return proxy;
        }
    }

    private static Object getProxyTargetObject(Object proxy) throws Exception {
        Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);
        AopProxy aopProxy = (AopProxy) h.get(proxy);
        Field target = aopProxy.getClass().getDeclaredField("target");
        target.setAccessible(true);
        return target.get(aopProxy);
    }
}
